package com.neiquan.backstage.event.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Paging;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.common.util.Strings;
import com.neiquan.backstage.event.EventService;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.Event;

@Controller
@RequestMapping(value = "eventAcion", produces = { "text/json;charset=UTF-8" })
public class EventAction {
	private static Class<?> poc = Event.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private EventService eventService;

	/**
	 * 添加Event
	 */
	@ResponseBody
	@RequestMapping(value = { "addEvent" })
	public String add(String name, String pic, String content, Integer applyAtatus, String startTime, String endTime, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		Event entity = new Event();
		if (eventService.queryByName(Strings.trimAndNotNull(name), memberId) != null) {
			return CommonResp.buildErrorResp(BackendErrorCode.already_exist).toJsonString();
		}
		entity.setName(Strings.trimAndNotNull(name));
		entity.setPic(pic);
		entity.setContent(Strings.trimAndNotNull(content));
		entity.setApplyAtatus(applyAtatus);
		try {
			if (applyAtatus == 1) {
				DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
				entity.setStartTime(dateFormat.parse(Strings.trimAndNotNull(startTime)).getTime());
				entity.setEndTime(dateFormat.parse(Strings.trimAndNotNull(endTime)).getTime());
			}
		} catch (ParseException e) {
			return CommonResp.buildErrorResp(e).toJsonString();
		}
		entity.setIusseTime(System.currentTimeMillis());
		entity.setMemberId(memberId);
		eventService.add(entity);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 分页查询
	 */
	@ResponseBody
	@RequestMapping(value = { "list" })
	public String list(int pageIndex, int pageSize, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Criterion criterion = Restrictions.eq("memberId", loginedUser.getMemberId());
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("eventId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, pageIndex, pageSize);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	/**
	 * 通过Id查询Event
	 */
	@ResponseBody
	@RequestMapping(value = { "queryById" })
	public String queryById(int id) {
		Event entity = eventService.queryById(id);
		if (entity == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		return CommonResp.buildSuccessResp(entity).toJsonString();
	}

	/**
	 * 修改Event
	 */
	@ResponseBody
	@RequestMapping(value = { "edit" })
	public String edit(Integer id, String name, String pic, String content, Integer applyAtatus, String startTime, String endTime, HttpSession session) {
		Event toUpdate = eventService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (StringUtils.isNoneBlank(name)) {
			toUpdate.setName(Strings.trimAndNotNull(name));
		}
		if (StringUtils.isNoneBlank(pic)) {
			toUpdate.setPic(Strings.trimAndNotNull(pic));
		}
		if (StringUtils.isNoneBlank(content)) {
			toUpdate.setContent(Strings.trimAndNotNull(content));
		}
		if (null != applyAtatus) {
			toUpdate.setApplyAtatus(applyAtatus);
		}
		try {
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			if (StringUtils.isNoneBlank(startTime)) {
				toUpdate.setStartTime(dateFormat.parse(Strings.trimAndNotNull(startTime)).getTime());
			}
			if (StringUtils.isNoneBlank(endTime)) {
				toUpdate.setEndTime(dateFormat.parse(Strings.trimAndNotNull(endTime)).getTime());
			}
		} catch (ParseException e) {
			return CommonResp.buildErrorResp(e).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 条件查询Event
	 */
	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String name, String startTime, String endTime, HttpSession session) throws ParseException {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", memberId));
		if (StringUtils.isNoneBlank(name)) {
			criterions.add(Restrictions.like("name", "%" + name + "%"));
		}
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		try {
			if (StringUtils.isNoneBlank(startTime)) {
				criterions.add(Restrictions.ge("startTime", dateFormat.parse(startTime).getTime()));
			}
			if (StringUtils.isNoneBlank(endTime)) {
				criterions.add(Restrictions.le("endTime", dateFormat.parse(endTime).getTime()));
			}
		} catch (ParseException e) {
			return CommonResp.buildErrorResp(BackendErrorCode.date_format_error).toJsonString();
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("eventId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	/**
	 * 删除Event
	 */
	@ResponseBody
	@RequestMapping(value = { "remove" })
	public String remove(int id) {
		Event entity = eventService.queryById(id);
		if (entity == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(entity);
		return CommonResp.buildSuccessResp().toJsonString();
	}
}
